#include <CompressorDocumentStorages.hpp>
#include <stdio.h>
#include <Types.h>
#include <FSDumper.hpp>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <FTSSException.hpp>
#include <MemoryDocumentInfoStorage.hpp>
#include <Util.hpp>
using namespace FTSS;

int main(int argc, char **argv){
	// argument parsing
	if (argc < 3){
		fprintf(stderr, "usage : data_directory file_to_delete_list.txt\n");
		return EX_USAGE; 
	}

	try{
		FILE * F = fopen(argv[2], "rb");
		if (F == NULL) { 
			fprintf(stderr, "ERROR: Cannot open file `%s' for reading.\n", argv[2]);
			return EX_DATAERR;
		}

		INT_64 iFileHandle;

		// opening current version of Document Info Database
 		fprintf(stdout, "Uncompressed document properties storage..."); fflush(stdout);
		MemoryDocumentInfoStorage  oFileIndexStorage;
       		fprintf(stdout, "OK\n");

		iFileHandle = open(DirFilePath(argv[1], "DocumentsDB.ftss").c_str(), O_RDONLY, 0644);
		if (iFileHandle != -1){
			FSDumper oDumper(iFileHandle);
			if (oFileIndexStorage.Restore(&oDumper) == -1){
				fprintf(stderr, "Cannot restore index `%s'.\n", argv[2]);
				return EX_SOFTWARE;
			}	
			close(iFileHandle);
 		}else { 
			fprintf(stderr, "Cannot open index file.\n");
			return EX_SOFTWARE; 
		}


		UINT_64 current_id;
		while(fscanf(F, "%llu", &current_id) != EOF){
			fprintf(stderr, "current_id=%lld\n", current_id);
			oFileIndexStorage.DeleteDocument(current_id);
		}
		fclose(F);

		iFileHandle = open(DirFilePath(argv[1], "DocumentsDB.ftss").c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
		if (iFileHandle != -1){       
			FSDumper oDumper(iFileHandle);
			if (oFileIndexStorage.Dump(&oDumper) != 0) { fprintf(stdout, "ERROR: Cannot dump document info!\n"); }
			close(iFileHandle);
			}else { 
				fprintf(stdout, "ERROR: Cannot open document info file for writing!\n");
		}
	



	//	oFileIndexStorage.compressInfoStorage();
		CompressorDocumentStorage oCompressor;
		oCompressor.compress(argv[1], &oFileIndexStorage);
		
		iFileHandle = open(DirFilePath(argv[1], "DocumentsDB_compressed.ftss").c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
		if (iFileHandle != -1)
	        {
			FSDumper oDumper(iFileHandle);
	                if (oFileIndexStorage.Dump(&oDumper) != 0) { fprintf(stdout, "ERROR: Cannot dump document info!\n"); }
		             	close(iFileHandle);
			}else { 
				fprintf(stdout, "ERROR: Cannot open document info file for writing!\n"); 
			}
		}
	catch (LogicException & e)
	{
		fprintf(stderr, "ERROR: %s!\n", e.what());
	        return EX_SOFTWARE;
	}
	catch (UnixException & e)
	{
		fprintf(stderr, "ERROR: %s!\n", e.what());
		return EX_SOFTWARE;
	}
	catch(...)
	{
		fprintf(stderr, "ERROR\n");
		return EX_SOFTWARE;
	}
	return EX_OK;
}
